class New {
    constructor() {
        this.newList = document.querySelector('.paging_list')
        this.init()
    }
    init() {
        this.request()
    }
    request() {
        pAjax({ url: '../libs/goods.json' })
            .then(res => {
                let data = JSON.parse(res)
                data = data.slice(700, 900)
                this.render(data)
            })
    }
    render(data) {
        data.forEach(item => {
            if (item.is_hot == true) {
                this.newList.innerHTML += `
                    <li>
                        <a href="./details.html?id=${item.goods_id}">
                            <img src="${item.img_small_logo}">
                        </a>
                        <div class='text'>
                            <span class="title">${item.title}</span>
                            <div class="price">
                                <b>${item.price}</b>
                                <button data-id=${item.goods_id}>+</button>
                            </div>
                        </div>
                    </li>
                `
            }
        })
        this.bindHtml(data)
        $(".paging_list").paging({
            PageNum: 20, //每页显示数目
            pageMax: true, //按钮长度是否显示
            pageMaxHideShow: false, //在最后一个的时候是否隐藏按钮长度
            pageDownUpHide: false, //到第一个或最后一个是否让上一页或下一页消失
            pageInput: true, //是否使用文本框输入跳转
            pagingBtnHide: false, //是否让按钮变为一个
            pagingBtnPaging: true,//按钮是否分页
            pagingDisplay: "block"//显示的属性，弹性盒子还是块化
        })
    }
    bindHtml(data) {
        this.newList.addEventListener('click', (e) => {
            let target = e.target || e.srcElement
            if (target.nodeName == 'BUTTON') {
                if (getCookie('username') == undefined || getCookie('password') == undefined) {
                    location.href = './login.html'
                } else {
                    let id = target.dataset.id - 0
                    let goods = data.find(item => { return item.goods_id == id })
                    let list = JSON.parse(localStorage.getItem('cart')) || []
                    if (!list.length) {
                        goods.cart_number = 1
                        list.push(goods)
                        console.log(list)
                    } else {
                        let res = list.some(item => { return item.goods_id == id })
                        if (res) {
                            let index = list.findIndex(item => { return item.goods_id == id })
                            list[index].cart_number++
                        } else {
                            goods.cart_number = 1
                            list.push(goods)
                        }
                    }
                    localStorage.setItem('cart', JSON.stringify(list))
                    window.totalNum()
                }
            }
        })
    }
}
new New()